package com.example.aop.config;



import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SimpleAspect {
    //拦截包位置
    @Pointcut("execution(* com.example.aop.service..*.*(..))")
    private void pointcut(){

    }
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Exception{
        String methodName = proceedingJoinPoint.getSignature().getName();
        System.err.println("执行"+methodName+"环绕通知开始");
        try {
            long startTime = System.currentTimeMillis();
            //执行目标方法
            Object result = proceedingJoinPoint.proceed();
            long endTime = System.currentTimeMillis();
            System.err.println("最终耗时"+(endTime - startTime)+"毫秒");
            return result;
        }catch (Throwable throwable){
            throwable.printStackTrace();
            throw new Exception("方法执行异常");
        }

    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        String methonName = joinPoint.getSignature().getName();
        System.err.println("执行"+methonName+"的前置通知@before");
    }
    @After("pointcut()")
    public void after(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.err.println("执行"+methodName+"的后置通知@After");
    }
    @AfterReturning("pointcut()")
    public void afterReturning(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.err.println("执行"+methodName+"d后置返回通知@Returning");
    }
    @AfterThrowing("pointcut()")
    public void afterThrowing(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.err.println("执行"+methodName+"的异常返回通知@AfterThrowing");
    }
}